package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.PurchaseAddDto;
import com.tticar.invmanager.entity.vo.PurchaseGoodsDto;
import com.tticar.invmanager.mapper.SaleReturnMapper;
import com.tticar.invmanager.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 销售退货表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2019-01-04
 */
@Service
public class SaleReturnServiceImpl extends ServiceImpl<SaleReturnMapper, SaleReturn> implements ISaleReturnService {
    @Autowired
    private ICodeCounterService codeCounterService;
    @Autowired
    private IInRepositoryDetailService inRepositoryDetailService;
    @Autowired
    private IRepositoryCountService repositoryCountService;
    @Autowired
    private IMSalesService salesService;
    @Autowired
    private IMSalesDetailService salesDetailService;
    @Autowired
    private IMMaterielSkuService skuService;
    @Autowired
    private IMMaterielService materielService;

    @Override
    public Page selectPage(SaleReturn saleReturn, MyPage<SaleReturn> page) {
        Wrapper wrapper = new EntityWrapper();
        //wrapper.like(Strings.isNotEmpty(saleReturn.getName()), SaleReturn.NAME, saleReturn.getName());
        List<Map> maps = this.baseMapper.querySaleReturnList(page, saleReturn);
        page.setRecords(maps);
        return page;
    }
    @Override
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            SaleReturn saleReturn = new SaleReturn();
            saleReturn.setId(id);
            saleReturn.setStatus(-1);
            list.add(saleReturn);
        }
        this.updateBatchById(list);
    }

    @Override
    public List<Map> detailGoodsList(String code) {
        return this.baseMapper.saleReturnDetailGoodsList(code);
    }

    @Override
    public List<Map> getSaleDetailList(String saleReturnCode) {
        return this.baseMapper.getSaleDetailList(saleReturnCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inRepositoryForSaleReturn(String saleReturnCode, List<PurchaseGoodsDto> goodsList, BigDecimal realPay, BigDecimal totalMoney, Integer payStatus, String remark) {
        if (realPay == null) {
            realPay = BigDecimal.ZERO;
        }
        Wrapper wra = new EntityWrapper<>();
        wra.eq("code", saleReturnCode);
        List<SaleReturn> saleReturns = selectList(wra);
        Date now = new Date();
        String rkCode = codeCounterService.getOrderCode(CodeType.RK);
        for (SaleReturn saleReturn : saleReturns) {
            for (PurchaseGoodsDto dto : goodsList) {
                if (saleReturn.getSkuId().equals(dto.getSkusId())) {
                    saleReturn.setRepositoryStatus(1);
                    saleReturn.setCount(dto.getCount());
                    saleReturn.setUnitPrice(new BigDecimal(dto.getAmountActual()));

                    saleReturn.setPayStatus(payStatus);
                    saleReturn.setRealPay(realPay);
                    saleReturn.setRemark(remark);
                    if (realPay != null && realPay.compareTo(totalMoney) > -1) {
                        saleReturn.setPayStatus(1);
                    } else {
                        saleReturn.setNeedPay(totalMoney.subtract(realPay));
                    }

                    //入库
                    InRepositoryDetail inDetail = new InRepositoryDetail();
                    inDetail.setSkuId(saleReturn.getSkuId());
                    inDetail.setCode(rkCode);
                    inDetail.setBuszId(saleReturn.getId());
                    inDetail.setProviderId(saleReturn.getCustomId());
                    inDetail.setWearhouseId(saleReturn.getRepositoryId());
                    inDetail.setOrderTime(saleReturn.getOrderTime());
                    inDetail.setType(6);
                    inDetail.setCount(saleReturn.getCount());
                    inDetail.setRemark(saleReturn.getRemark());
                    inDetail.setStatus(0);
                    inDetail.setCtime(now);
                    inDetail.setUsername(MySecurityUtils.currentUser().getUsername());
                    inRepositoryDetailService.insertOrUpdate(inDetail);

                    repositoryCountService.updateRepositoryCount(saleReturn.getSkuId(), inDetail.getWearhouseId(), inDetail.getCount());
                }
            }
        }
        this.updateBatchById(saleReturns);
    }


    /**
     * 结算
     * */
    @Override
    public void endCountSaleReturn(String saleReturnCode, BigDecimal realPay, BigDecimal totalMoney, Integer payStatus, String remark) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("code", saleReturnCode);
        List<SaleReturn> saleReturns = selectList(wrapper);
        for (SaleReturn saleReturn : saleReturns) {
//            saleReturn.setPayStatus(payStatus);
//            if (realPay.compareTo(totalMoney) >= 0) {
                saleReturn.setPayStatus(1);
//            }
//            saleReturn.setRemark(remark);
            saleReturn.setRealPay(totalMoney);
        }

        this.updateBatchById(saleReturns);
    }

    /**
     * 撤销入库
     * */
    @Override
    @Transactional
    public void cancelInForSaleReturn(String saleReturnCode) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("code", saleReturnCode);
        List<SaleReturn> saleReturns = selectList(wrapper);
        List idList = new ArrayList<>();
        for (SaleReturn entity : saleReturns) {
            entity.setRepositoryStatus(0);
            entity.setRealPay(BigDecimal.ZERO);
            entity.setPayStatus(0);
            idList.add(entity.getId());
        }
        updateBatchById(saleReturns);

        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("type", 6);
        wrapper1.in("busz_id", idList);
        wrapper1.eq("status", 0);
        List<InRepositoryDetail> inRepositoryDetails = inRepositoryDetailService.selectList(wrapper1);
        for (InRepositoryDetail inRepositoryDetail : inRepositoryDetails) {
            inRepositoryDetail.setStatus(-1);
            repositoryCountService.updateRepositoryCount(inRepositoryDetail.getSkuId(), inRepositoryDetail.getWearhouseId(), inRepositoryDetail.getCount()*-1);
        }
        inRepositoryDetailService.updateBatchById(inRepositoryDetails);

    }

    /**
     * 撤销结算
     * */
    @Override
    public void cancelEndCount(String saleReturnCode) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("code", saleReturnCode);
        List<SaleReturn> saleReturns = selectList(wrapper);
        for (SaleReturn entity : saleReturns) {
            entity.setPayStatus(0);
            entity.setRealPay(BigDecimal.ZERO);
        }
        updateBatchById(saleReturns);
    }


    @Override
    @Transactional
    public void addSaleReturn(PurchaseAddDto dto) throws ParseException {
        if (dto.getRealPay() == null) {
            dto.setRealPay(BigDecimal.ZERO);
        }
        List<PurchaseGoodsDto> goodsList = dto.getGoodsList();
        Date now = new Date();
        Date inDate = new Date();
        inDate.setHours(0);
        inDate.setMinutes(0);
        inDate.setSeconds(0);
        String xtCode = codeCounterService.getOrderCode(CodeType.XT);
        String rkCode = codeCounterService.getOrderCode(CodeType.RK);
        for (PurchaseGoodsDto goodsDto : goodsList) {
            SaleReturn saleReturn = new SaleReturn();
            saleReturn.setCode(xtCode);
            saleReturn.setCtime(now);
            saleReturn.setRepositoryId(goodsDto.getRepositoryId());
            saleReturn.setCustomId(dto.getRelativeId());
            saleReturn.setCount(goodsDto.getCount());
            saleReturn.setSkuId(goodsDto.getSkusId());
            saleReturn.setOrderTime(DateUtil.StringToDate(dto.getPtime(), DateStyle.YYYY_MM_DD));
            saleReturn.setUnitPrice(new BigDecimal(goodsDto.getAmountActual()));
            saleReturn.setUsername(MySecurityUtils.currentUser().getUsername());
            saleReturn.setRepositoryStatus(dto.getType() == 0 ? 0 : 1);

            if (dto.getType() == 0) {
                saleReturn.setNeedPay(dto.getRealPay());
            } else {
                saleReturn.setPayStatus(dto.getPayStatus());
                if (dto.getRealPay() != null && dto.getRealPay().compareTo(dto.getTotalMoney()) > -1) {
                    saleReturn.setPayStatus(1);
                } else {
                    saleReturn.setNeedPay(dto.getTotalMoney().subtract(dto.getRealPay()));
                }
            }
            saleReturn.setRemark(dto.getRemark());
            saleReturn.setSettlementStatus(dto.getPayStatus());
            insert(saleReturn);

            //如果是生单并入库
            if (dto.getType() == 1) {
                InRepositoryDetail inDetail = new InRepositoryDetail();
                inDetail.setSkuId(saleReturn.getSkuId());
                inDetail.setCode(rkCode);
                inDetail.setBuszId(saleReturn.getId());
                inDetail.setProviderId(saleReturn.getCustomId());
//                    inDetail.setBatchNumber(detail.getBatchCode());
                inDetail.setWearhouseId(goodsDto.getRepositoryId());
//                    inDetail.setPositionId(kw.get("positionId"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                inDetail.setOrderTime(sdf.parse(dto.getPtime()));
                inDetail.setType(6);
                inDetail.setCount(saleReturn.getCount());
                inDetail.setStatus(0);
                inDetail.setCtime(now);
                inDetail.setUsername(MySecurityUtils.currentUser().getUsername());
                inRepositoryDetailService.insertOrUpdate(inDetail);

                repositoryCountService.updateRepositoryCount(saleReturn.getSkuId(), inDetail.getWearhouseId(), inDetail.getCount());
            }
        }


    }


    /**
     * 根据销售单进行整单退货
     * */
    @Override
    public String allReturnForSale(Long id) {
        MSales mSales = salesService.selectById(id);
        if (mSales.getOrderStatus() == 3) {
            throw new MyServiceException("此单已退货，请勿重复退货");
        }
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("sales_id", id);
        String orderCode = codeCounterService.getOrderCode(CodeType.XT);
        mSales.setOrderStatus(3);
        mSales.setReturnOrder(orderCode);
        salesService.updateById(mSales);
        List<MSalesDetail> mSalesDetails = salesDetailService.selectList(wrapper);
        for (MSalesDetail entity : mSalesDetails) {
            Wrapper wrapper1 = new EntityWrapper<>();
            wrapper1.eq("id", entity.getSkuId());
            MMaterielSku mMaterielSku = skuService.selectOne(wrapper1);
            Wrapper wrapper2 = new EntityWrapper<>();
            wrapper2.eq("id", mMaterielSku.getMid());
            MMateriel mMateriel = materielService.selectOne(wrapper2);
            SaleReturn saleReturn = new SaleReturn();
            saleReturn.setCustomId(mSales.getCusId());
            saleReturn.setCode(orderCode);
            saleReturn.setCount(entity.getNum());
            saleReturn.setUnitPrice(entity.getPrice());
            saleReturn.setOrderTime(new Date());
            saleReturn.setPayStatus(0);
            saleReturn.setRepositoryStatus(0);
            saleReturn.setSkuId(entity.getSkuId());
            saleReturn.setRepositoryId(mMateriel.getDefaultWhouseId());
            saleReturn.setUsername(MySecurityUtils.currentUser().getUsername());
            insert(saleReturn);
        }
        return orderCode;
    }
}
